package cn.zhqr.core.interceptor;

import cn.zhqr.common.exception.RepeatSubmissionException;
import cn.zhqr.common.external.cache.CacheKit;
import cn.zhqr.common.util.digest.MD5Utils;
import cn.zhqr.common.util.map.MapKit;
import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import org.apache.log4j.Logger;


/**
 * 防止重复提交拦截器
 * Created by charles on 2018/6/20.
 */
public class PreventRepeatSubmissionInterceptor implements Interceptor {
    private static Logger log = Logger.getLogger(PreventRepeatSubmissionInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        PreventRepeatSubmission anno = inv.getController().getClass().getAnnotation(PreventRepeatSubmission.class);
        if (anno == null) {
            anno = inv.getMethod().getAnnotation(PreventRepeatSubmission.class);
        }
        if (anno != null) {
            String params = JSON.toJSONString(MapKit.sortByKey(inv.getController().getParaMap()));
            String action_key = "prevent_repeat_submission_key_"
                    + inv.getControllerKey() + "/" + inv.getMethodName()
                    + "_" + MD5Utils.md5(params);

            Class method_class = inv.getMethod().getClass();

            synchronized (method_class) {
                Object value = CacheKit.use().get(action_key);

                if (value != null) {
                    throw new RepeatSubmissionException(anno.errorMsg(),
                            "Repeat Submission : " + inv.getControllerKey() + inv.getMethodName() + "."
                                    + inv.getControllerKey() + inv.getMethodName() + "（" + params + ")");
                }
                CacheKit.use().setEx(action_key, anno.minInterval(), inv.getController().getSession().getId());
            }
        }
        inv.invoke();
    }
}
